import {expect} from 'chai'
import * as sinon from 'sinon'
import axios from 'axios'
import * as chunkUpload from '../src/package-chunk-upload'
import {UploadInputs} from '../src/upload-inputs'
import mock from 'mock-fs'

describe('Package Chunk Upload', () => {
    let sandbox: sinon.SinonSandbox
    let axiosStub: sinon.SinonStub

    beforeEach(() => {
        sandbox = sinon.createSandbox()
        axiosStub = sandbox.stub(axios, 'request')
        mock({
            '/test/packages': {
                'test-artifact.tar.gz': Buffer.alloc(2 * 1024 * 1024 * 1024) // 2GB
            }
        })
    })

    afterEach(() => {
        sandbox.restore()
        mock.restore()
    })

    describe('MULTIPART_UPLOAD_THRESHOLD', () => {
        it('should be 800MB', () => {
            expect(chunkUpload.MULTIPART_UPLOAD_THRESHOLD).to.equal(
                800 * 1024 * 1024
            )
        })
    })

    describe('chunkUpload', () => {
        it('should throw error when credential is missing', async () => {
            const artifact: UploadInputs = {
                workDir: '/test/work',
                projectDir: '/test/project',
                artifact: 'test-artifact',
                artifactName: 'test-artifact.tar.gz',
                artifactPath: 'test.tar.gz',
                artifactVersion: 'v1.0.0',
                uploadType: 'packages',
                gitIgnore: undefined,
                dateTime: '20240101',
                repoId: 'test-repo',
                credential: undefined, // Missing credential
                packageHost: 'https://packages.example.com',
                orgId: 'test-org',
                regionId: 'cn-hangzhou',
                fileId: 'test-file-id',
                fileParentId: 'test-parent-id',
                bucketName: 'test-bucket',
                accessKeyId: undefined,
                accessKeySecret: undefined,
                token: undefined,
                stepIdentifier: 'test-step',
                artifactFullName: '/test/packages/test-artifact.tar.gz',
                fileMD5: '5d41402abc4b2a76b9719d911017c592',
                metaUpload: undefined,
                authorization: undefined,
                baseUrl: undefined
            }

            try {
                await chunkUpload.chunkUpload(artifact)
                expect.fail('Should have thrown an error')
            } catch (error: any) {
                expect(error.message).to.equal('packages user credential is empty')
            }
        })
    })
})

